﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsForgeReboot.Framework.Entities;
using CookComputing.XmlRpc;
using MsForgeReboot.Framework.Interfaces;
using MsForgeReboot.Framework.TownCrierChannelTools;

namespace MsForgeReboot.Framework.TownCrierChannels {
    public class MetaWeblogChannel : IChannel {

        //private IRestClient _client;
        //private IRestRequest _request;
        //private ChannelSettings _settings;
        private IMetaWeblog _proxy;
        private MetaweblogChannelSection _settings;
        public Event Source { get; set; }


        public MetaWeblogChannel() :
            this(XmlRpcProxyGen.Create<IMetaWeblog>(), "MetaweblogChannelSection") { }

        public MetaWeblogChannel(IMetaWeblog proxy, string sectionName) {
            _proxy = proxy;
            _settings = System.Configuration.ConfigurationManager.GetSection(sectionName) as MetaweblogChannelSection;
        }

        public MetaWeblogChannel(IMetaWeblog proxy, MetaweblogChannelSection settings) {
            _proxy = proxy;
            _settings = settings;
        }



        public DeliveryResult DeliverEvent(Event source) {
            //throw new NotImplementedException();
            if (source == null)
                throw new ArgumentException("Event must be present in the call", "Event");

            MsForgeReboot.Framework.TownCrierChannelTools.Post post = new MsForgeReboot.Framework.TownCrierChannelTools.Post();
            post.title = source.Title;
            post.description = source.Body;
            //post.dateCreated = new XmlRpcDateTime(DateTime.Now);
            post.dateCreated = DateTime.Now;
            post.categories = new string[] { "usergroups" };

            _proxy.Url = _settings.ApiBaseUrl.Value;
            DeliveryResult result = new DeliveryResult { DeliveryChannel = "Metaweblog API" };

            try {
                var postid = _proxy.newPost(_settings.BlogID, _settings.HttpBasicAuth.Username, _settings.HttpBasicAuth.Password, post, true);
                result.Message = postid;
                result.Success = true;
            } catch (Exception e) {
                result.Message = e.Message;
                result.Success = false;
            }
            result.Status = DeliveryStatus.Completed;
            result.DeliveredOn = DateTime.UtcNow;
            return result;
           
        }
    }
}
